var categories_json;
var vendors_json;
var accounts_json;
var update_transaction = false;

function getText(node) {

    if (node.nodeType === 3) {
        return jQuery.trim(node.data);
    }

    var txt = '';

    if (node = node.firstChild) do {
        txt += getText(node);
    } while (node = node.nextSibling);

    return txt;

}

$(function(){
		$('#tabs').tabs();
		$("#main_menu").menu();

		$("#flex_transactions").flexigrid
		(
			{
			url: '',
			method: 'GET',
			dataType: 'json',
			colModel : [
				{display: 'ID', name : 'id', width : 1, sortable : true, align: 'center', hide: true},
				{display: 'Account ID', name : 'account_id', width : 1, sortable : true, align: 'center', hide: true},
				{display: 'FITID', name : 'fitid', width : 1, sortable : true, align: 'center', hide: true},
			    {display: 'Date', name : 'posted', width : 100, sortable : true, align: 'left'},
				{display: 'Name', name : 'name', width : 500, sortable : true, align: 'left'},
				{display: 'Amount', name : 'amt', width : 70, sortable : true, align: 'right',process:format_amt},
				{display: 'Type', name : 'type', width : 70, sortable : true, align: 'left'},
				{display: 'Vendor', name : 'vendor',width : 120, align: 'left',process:show_vendor},
				{display: 'Category', name : 'category',width : 120, align: 'left',process:show_category},
				{display: 'Transfer ID', name : 'transfer_id', hide: true},
				{display: 'Transfer ID', name : 'transfer_from_id', hide: true},
				{display: 'Vendor ID', name : 'vendor_id', hide: true},
				{display: 'Category ID', name : 'category_id', hide: true}
				],
			buttons : [	{name: 'Manual', bclass: 'add', onpress: add_transaction_dlg},
			           	{name: 'Edit', bclass: 'edit', onpress: edit_transaction_dlg},
			           	{name: 'Create Rule', bclass: 'add', onpress: add_rule_from_transaction_dlg}],
			singleSelect: true,
			sortname: "posted",
			sortorder: "desc",
			title: "Transactions",
			usepager: true,
			useRp: true,
			rp: 20,
			showTableToggleBtn: true,
			hideOnSubmit: false,
			height: 610
			}
		);
		$("#flex_accounts").flexigrid
		(
			{
			url: 'command/get_account_list?flex=1',
			method: 'GET',
			dataType: 'json',
			colModel : [
				{display: 'ID', name : 'id', width : 1, sortable : true, align: 'center', hide: true},
				{display: 'Name', name : 'nick', width : 150, sortable : true, align: 'left'},
				{display: 'Account', name : 'name', width : 200, sortable : true, align: 'left'},
				{display: 'Type', name : 'type', width : 70, sortable : true, align: 'left'}
				],
			buttons : [{name: 'Edit', bclass: 'edit', onpress: edit_account_dlg},
			           {name: 'Upload', bclass: 'upload', onpress: upload_file}],
			singleSelect: true,
			sortname: "nick",
			sortorder: "asc",
			title: "Accounts",
			usepager: true,
			useRp: true,
			rp: 25,
			showTableToggleBtn: true,
			hideOnSubmit: false,
			height: 610
			}
		);
		
		$( "#transaction_dlg" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				Cancel: function() {
				$( this ).dialog( "close" );
				},
				"Save": function() {
					$.ajax({
						url: 'command/save_transaction?id=' + $('#transaction_dlg #id').val() + '&name=' + $('#transaction_dlg #name').val() + '&amt=' + $('#transaction_dlg #amt').val() + '&date=' + $('#transaction_dlg #date').val() + '&category=' + $('#transaction_dlg #category_list').children(":first").val() + '&vendor=' + $('#transaction_dlg #vendor_list').children(":first").val() + "&acct=" + $('#account_list').val() + "&type=" + $('#creditdebitradio').val(), 
						success:function(data) {
							$("#transaction_dlg").dialog( "close" );
							$("#flex_transactions").flexReload();
							}
						});
				}
			}
		});

		$( "#account_dlg" ).dialog({
			autoOpen: false,
			height: 200,
			width: 350,
			modal: true,
			buttons: {
				Cancel: function() {
				$( this ).dialog( "close" );
				},
				"Save": function() {
					$.ajax({
						url: 'command/save_account?id=' + $('#account_dlg #id').text() + '&nick=' + $('#account_dlg #nick').val(),
						success:function(data) {
							$("#account_dlg").dialog( "close" );
							$("#flex_accounts").flexReload();
							fill_account($('#account_list'));
							}
						});
				}
			}
		});

		$( "#upload_dlg" ).dialog({
			autoOpen: false,
			height: 200,
			width: 350,
			modal: true,
			buttons: {
				Cancel: function() {
					$( this ).dialog( "close" );
				},
				"Save": function() {
					$( "#upload_dlg form" ).submit();
				}
			}
		});

		$( "#vendor_dlg" ).dialog({
			autoOpen: false,
			height: 200,
			width: 350,
			modal: true,
			buttons: {
				Cancel: function() {
				$( this ).dialog( "close" );
				},
				"Save": function() {
					$.ajax({
						url: 'command/save_vendor?id=' + $('#vendor_dlg #id').val() + '&name=' + $('#vendor_dlg #name').val(),
						success:function(data) {
							$("#vendor_dlg").dialog( "close" );
							$("#flex_vendors").flexReload();
							load_vendor_list();
							if(update_transaction){
								set_vendor(update_transaction,data.id, 0);
								update_transactions = false;
								}
							}
						});
				}
			}
		});

		$( "#category_dlg" ).dialog({
			autoOpen: false,
			height: 200,
			width: 350,
			modal: true,
			buttons: {
				Cancel: function() {
				$( this ).dialog( "close" );
				},
				"Save": function() {
					$.ajax({
						url: 'command/save_category?id=' + $('#category_dlg #id').val() + '&name=' + $('#category_dlg #name').val() + '&type=' + $('#category_dlg #categories_types_list').val(),
						success:function(data) {
							$("#category_dlg").dialog( "close" );
							load_categories_list();
							if(update_transaction)
								set_category(update_transaction,data.id,0);
								update_transactions = false;
							}
						});
				}
			}
		});

		$( "#rule_dlg" ).dialog({
			autoOpen: false,
			height: 200,
			width: 350,
			modal: true,
			buttons: {
				Cancel: function() {
					$( this ).dialog( "close" );
				},
				"Save": function() {
					$.ajax({
						url: 'command/save_rule?id=' + $('#rule_dlg #id').val() + '&name=' + $('#rule_dlg #name').val() + '&amt=' + $('#rule_dlg #amt').val() + '&vendor=' + $('#rule_dlg #vendor_list').children(":first").val() + '&category=' + $('#rule_dlg #category_list').children(":first").val(),
						success:function(data) {
							$("#rule_dlg").dialog( "close" );
							$("#flex_rules").flexReload();
							}
						});
				}
			}
		});

		$( "#transfer_dlg" ).dialog({
			autoOpen: false,
			height: 250,
			width: 350,
			modal: true,
			buttons: {
				Cancel: function() {
					$( this ).dialog( "close" );
				},
				"Save": function() {
					$.ajax({
						url: 'command/save_transfer?from_transaction_id=' + $('#transfer_dlg #from_transaction_id').val() + '&to_transaction_id=' + $('#transfer_dlg #to_transaction_id').val(),
						success:function(data) {
							$("#transfer_dlg").dialog( "close" );
							load_transactions();
							}
						});
				}
			}
		});

		
		$("#flex_transfers").flexigrid
		(
			{
			url: 'command/get_transfer_list?flex=1',
			method: 'GET',
			dataType: 'json',
			colModel : [
				{display: 'ID', name : 'id', width : 1, sortable : true, align: 'center', hide: true},
				{display: 'From', name : 'nick_from', width : 150, sortable : true, align: 'left'},
				{display: 'To', name : 'nick_to', width : 200, sortable : true, align: 'left'},
				{display: 'Amount', name : 'amt', width : 70, sortable : true, align: 'left'},
				{display: 'Date', name : 'posted_from', width : 70, sortable : true, align: 'left'}
				],
			buttons : [{name: 'Edit', bclass: 'edit', onpress: edit_transfer_dlg},
			           {name: 'Delete', bclass: 'delete', onpress: delete_transfer_dlg}],
			singleSelect: true,
			sortname: "posted_from",
			sortorder: "asc",
			title: "Trasfers",
			usepager: true,
			useRp: true,
			rp: 25,
			showTableToggleBtn: true,
			hideOnSubmit: false,
			height: 610
			}
		);
		
		$("#flex_vendors").flexigrid
		(
			{
			url: '',
			method: 'GET',
			dataType: 'json',
			colModel : [
				{display: 'ID', name : 'id', width : 1, sortable : true, align: 'center', hide: true},
				{display: 'Name', name : 'name', width : 150, sortable : true, align: 'left'}
				],
			buttons : [	{name: 'Add', bclass: 'add', onpress: add_vendor_dlg},
						{name: 'Edit', bclass: 'edit', onpress: edit_vendor_dlg}
						],
			singleSelect: true,
			sortname: "name",
			sortorder: "asc",
			title: "Vendors",
			usepager: true,
			useRp: true,
			rp: 25,
			showTableToggleBtn: true,
			hideOnSubmit: false,
			height: 610
			}
		);
		$("#flex_categories").flexigrid
		(
			{
			url: '',
			method: 'GET',
			dataType: 'json',
			colModel : [
				{display: 'ID', name : 'c.id', width : 1, sortable : true, align: 'center', hide: true},
				{display: 'Name', name : 'c.name', width : 150, sortable : true, align: 'left'},
				{display: 'Type', name : 't.name', width : 70, sortable : true, align: 'left'}
				],
			buttons : [	{name: 'Add', bclass: 'add', onpress: add_category_dlg},
						{name: 'Edit', bclass: 'edit', onpress: edit_category_dlg},
						{name: 'Delete', bclass: 'delete', onpress: edit_category_dlg}
						],
			singleSelect: true,
			sortname: "c.name",
			sortorder: "asc",
			title: "Categories",
			usepager: true,
			useRp: true,
			rp: 25,
			showTableToggleBtn: true,
			hideOnSubmit: false,
			height: 610
			}
		);
		$("#flex_rules").flexigrid
		(
			{
			url: 'command/get_rule_list?flex=1',
			method: 'GET',
			dataType: 'json',
			colModel : [
				{display: 'ID', name : 'r.id', width : 1, sortable : true, align: 'center', hide: true},
				{display: 'Name', name : 'r.name', width : 150, sortable : true, align: 'left'},
//				{display: 'Account', name : 'a.account', width : 150, sortable : true, align: 'left', hide: true},
				{display: 'Amount', name : 'r.amt', width : 150, sortable : true, align: 'left'},
				{display: 'VendorId', name : 'v.id', width : 1, hide: true},
				{display: 'Vendor', name : 'v.name', width : 70, sortable : true, align: 'left'},
				{display: 'CategoryID', name : 'c.id', width : 1, hide: true},
				{display: 'Category', name : 'c.name', width : 70, sortable : true, align: 'left'}
				],
			buttons : [	{name: 'Add', bclass: 'add', onpress: add_rule_dlg},
						{name: 'Edit', bclass: 'edit', onpress: edit_rule_dlg},
						{name: 'Delete', bclass: 'delete', onpress: delete_rule_dlg},
						{name: 'Run', bclass: 'run_rules', onpress: run_rules}
						],
			singleSelect: true,
			sortname: "r.name",
			sortorder: "asc",
			title: "Rules",
			usepager: true,
			useRp: true,
			rp: 25,
			showTableToggleBtn: true,
			hideOnSubmit: false,
			height: 610
			}
		);
		load_categories_list();
		load_vendor_list();
		load_account_list();
		load_category_type_list();
		fill_account($('#account_list'));
		load_transactions();
		$('#account_list').change(function(e) { return load_transactions(); });
		$('#uncategorized').change(function(e) { return load_transactions(); });
		$('#transfer_dlg #to_account_list').change(function(e) { return get_transfer(); });
		$('#transaction_dlg #name').change(function(e) { return check_rule(); });
		
});
function format_amt(celDiv,amt){
	celDiv.innerHTML = "$" + Number(celDiv.innerHTML).toFixed(2);
}

function load_categories_list() {
	categories_json = load_abstract_list('category','categories', '#flex_categories')
}

function load_vendor_list() {
	vendors_json = load_abstract_list('vendor','vendors', '#flex_vendors')
}

function load_account_list() {
	accounts_json = load_abstract_list('account','accounts', 'flex_accounts')
}

function find_in_list(list_obj, id) {
	ret = null;
	$(list_obj).each(function()
	{
		if (this.id == id) 
			ret = this;
	});
	return ret;
}

function load_abstract_list(type, data_type, flex_name) {
	var ret = "";
	var url = 'command/get_'+ type + '_list';
	var flex = $(flex_name)
	flex.flexOptions({url: url + '?flex=1'}).flexReload();					
	$.ajax(
			{
				url: url,
				async : false,
				cache : false,
				dataType: "json",
				success:function(data)
				{ 
					ret = data[data_type];
				}
			});
	return ret;
}

function fill_account(ctrl, except){
	$(accounts_json).each(function()
	{
		if (except != this.id) {
			var option = $('<option />');
		    option.attr('value', this.id).text(this.nick);
		    ctrl.append(option);
		}
	});
}

function load_category_type_list() {
	$.ajax(
			{
				url: 'command/get_category_type_list?',
				async : false,
				cache : false,
				dataType: "json",
				success:function(data)
				{ 
					$('#categories_types_list').html("");
					$(data.category_types).each(function()
							{
							     var option = $('<option />');
							     option.attr('value', this.id).text(this.name);
							     $('#categories_types_list').append(option);
							 });
				}
			});
}


function show_vendor(celDiv,id, do_onchange){
	if (celDiv.innerHTML == '&nbsp;'){
		html = '<option value="-1">select ...</option><option value="-2">Add New...</option><option value="-3">Transfer...</option>';
		$(vendors_json).each(function()
			{
				html += '<option value="' + this.id + '">' + this.name + '</option>';
			});
		onChange = typeof do_onchange == 'undefined' ? " onChange='set_vendor(this.id,this.value,this)'" : "";
		celDiv.innerHTML = '<select id="' + id + '" class="vendors_dropdown"' + onChange + '>' + html + '</select>';
	}
}


function show_category(celDiv,id, do_onchange){
	if (celDiv.innerHTML == '&nbsp;'){
		html = '<option value="-1">select ...</option><option value="-2">Add New...</option>';
		$(categories_json).each(function()
			{
				html += '<option value="' + this.id + '">' + this.name + '</option>';
			});
		onChange = typeof do_onchange == 'undefined' ? " onChange='set_category(this.id,this.value, this)'" : "";
		celDiv.innerHTML = '<select id="' + id + '" class="categories_dropdown"' + onChange + '>' + html + '</select>';
	}
}

function load_transactions() {
	var url = 'command/get_transaction_list?account=' + $('#account_list').val() + "&flex=1" + "&uncat="+ $('#uncategorized').is(':checked');
	$("#flex_transactions").flexOptions({url: url}).flexReload();					
}

function reload_transactions() {
	$("#flex_transactions").flexReload();					
}
function add_transaction_dlg() {
	show_vendor($("#transaction_dlg #vendor_list").get(0),-1);
	show_category($("#transaction_dlg #category_list").get(0),-1, false);
	$("#transaction_dlg #creditdebitradio").show();
	$('#transaction_dlg').dialog( "open" );
}

function edit_transaction_dlg() {
	show_vendor($("#transaction_dlg #vendor_list").get(0),-1);
	show_category($("#transaction_dlg #category_list").get(0),-1, false);
	if ($("#flex_transactions .trSelected").length > 0) {
		row = $("#flex_transactions .trSelected")[0];
		$.ajax(
				{
					url: 'command/get_transaction?id=' + row.childNodes[0].firstChild.innerHTML,
					async : false,
					cache : false,
					dataType: "json",
					success:function(data)
					{ 
						$(data.transaction).each(function()
						{
							$("#transaction_dlg #id").val(this.tr_id);
							$("#transaction_dlg #name").val(this.tr_name);
							$("#transaction_dlg #amt").val(this.amt);
							$("#transaction_dlg #date").val(this.dt);
							$("#transaction_dlg #vendor_list").children(":first").val(this.ven_id)
							$("#transaction_dlg #category_list").children(":first").val(this.cat_id)
						});
						$("#transaction_dlg #creditdebitradio").hide();
						$('#transaction_dlg').dialog( "open" );
					}
				});
	}
                                         
}

function edit_account_dlg() {
	if ($("#flex_accounts .trSelected").length > 0) {
		row = $("#flex_accounts .trSelected")[0];
		$.ajax(
				{
					url: 'command/get_account?id=' + row.childNodes[0].firstChild.innerHTML,
					async : false,
					cache : false,
					dataType: "json",
					success:function(data)
					{ 
						$(data.account).each(function()
						{
							$('#account_dlg #id').text(this.id);
							$('#account_dlg #nick').val(this.nick);
							$('#account_dlg #name').text(this.name);
							$('#account_dlg #type').text(this.type);
						});
						$('#account_dlg').dialog( "open" );
					}
				});
	}
                                         
}
function upload_file() {
	$('#upload_dlg').dialog( "open" );
}
function add_vendor_dlg(){
	$('#vendor_dlg #id').val("-1");
	$('#vendor_dlg').dialog( "open" );
}
function edit_vendor_dlg() {
	if ($("#flex_vendors .trSelected").length > 0) {
		row = $("#flex_vendors .trSelected")[0];
		$.ajax(
				{
					url: 'command/get_vendor?id=' + row.childNodes[0].firstChild.innerHTML,
					async : false,
					cache : false,
					dataType: "json",
					success:function(data)
					{ 
						$(data.vendor).each(function()
						{
							i = Object.keys(this);
							$('#vendor_dlg #id').val(this.id);
							$('#vendor_dlg #name').val(this.name);
						});
						$('#vendor_dlg').dialog( "open" );
					}
				});
	}
                                         
}
function add_category_dlg(){
	$("#category_dlg #id").val("-1");
	$('#category_dlg').dialog( "open" );
}

function edit_category_dlg(){
	$('#category_dlg').dialog( "open" );
}

function set_category(transaction_id, value, td) {
	if(transaction_id == -1)
		return;
	if (value == -2) {
		update_transaction = transaction_id;
		add_category_dlg();
	}else if (value >-1) {
		rule_name = "";
		if (confirm("Would you like to create a rule?")) {
			transaction_name = $(td).parent().parent().prev().prev().prev().prev().text();
			rule_name = prompt("Rule Name",transaction_name);
		}
		$.ajax({
			url: 'command/save_transaction?id=' + transaction_id + '&category=' + value + "&rule_name=" + rule_name, 
			async : false,cache : false,
			success:function(data){ reload_transactions(); }});
	}
}

function set_vendor(transaction_id, value, td) {
	if(transaction_id == -1)
		return;
	if (value == -2) {
		update_transaction = transaction_id;
		add_vendor_dlg();
	}
	else if (value == -3) {
		amt = $(td).parent().parent().prev().prev().text()
		sent = $(td).parent().parent().prev().prev().prev().prev().text()
		add_transfer_dlg(transaction_id,amt,sent);
	}
	else if (value >-1) {
		$.ajax({
			url: 'command/save_transaction?id=' + transaction_id + '&vendor=' + value, 
			async : false,cache : false,
			success:function(data){ reload_transactions(); }});
	}
}
function add_rule_dlg(){
	$("#rule_dlg #id").val("-1");
	show_vendor($("#rule_dlg #vendor_list").get(0),-1, false);
	show_category($("#rule_dlg #category_list").get(0),-1, false);
	$('#rule_dlg').dialog( "open" );
}

function add_rule_from_transaction_dlg(){
	if ($("#flex_transactions .trSelected").length > 0) {
		row = $("#flex_transactions .trSelected")[0];
		show_vendor($("#rule_dlg #vendor_list").get(0),-1, false);
		show_category($("#rule_dlg #category_list").get(0),-1, false);
		$("#rule_dlg #id").val("-1");
		$("#rule_dlg #name").val(getText(row.children[4]));
		$("#rule_dlg #amt").val(getText(row.children[5]));
		$("#rule_dlg #vendor_list").children(":first").val(getText(row.children[11]))
		$("#rule_dlg #category_list").children(":first").val(getText(row.children[12]))
		$('#rule_dlg').dialog( "open" );
	}
}

function edit_rule_dlg(){
	if ($("#flex_rules .trSelected").length > 0) {
		row = $("#flex_rules .trSelected")[0];
		show_vendor($("#rule_dlg #vendor_list").get(0),-1, false);
		show_category($("#rule_dlg #category_list").get(0),-1, false);
		$("#rule_dlg #id").val(getText(row.children[0]));
		$("#rule_dlg #name").val(getText(row.children[1]));
		$("#rule_dlg #amt").val(getText(row.children[2]));
		$("#rule_dlg #vendor_list").children(":first").val(getText(row.children[3]))
		$("#rule_dlg #category_list").children(":first").val(getText(row.children[5]))
		$('#rule_dlg').dialog( "open" );
	}
}

function run_rules(){
	$.ajax({
		url: 'command/run_rules?all', 
		async : false,cache : false,
		success:function(data){ 
			load_transactions();
			alert('Rules applied'); 
			}});
	
}

function delete_something_dlg(something){
	var selections = $("#flex_" + something + "s .trSelected")
	if (selections.length > 0) {
		if (confirm("Are you sure you want to delete the " + something +"?")) {
			$.ajax({
				url: 'command/delete_' + something +'?id=' + selections[0].firstChild.firstChild.innerHTML,
				success:function(data) {
					$("#flex_" + something + "s").flexReload();
					}
				});
		}
	}
}
function delete_rule_dlg(){
	return delete_something_dlg("rule");
}

function delete_transfer_dlg(){
	return delete_something_dlg("transfer");
}

function edit_transfer_dlg(){}

function add_transfer_dlg(from_transaction_id, amt, sent_date){
	acct_id = $('#account_list').val()
	acct= find_in_list(accounts_json,acct_id);
	row = $("#flex_transactions .trSelected")[0];
	$('#transfer_dlg #id').val("-1");
	$('#transfer_dlg #acct_id').val(acct_id);
	$('#transfer_dlg #from_transaction_id').val(from_transaction_id);
	$('#transfer_dlg #from').text(acct.nick);
	$('#transfer_dlg #amt').text(amt);
	$('#transfer_dlg #sent').text(sent_date);
	$('#transfer_dlg #to_account_list').find('option').remove().end().append('<option/>')
	fill_account($('#transfer_dlg #to_account_list'),acct_id);
	$('#transfer_dlg').dialog( "open" );
}

function get_transfer() {
	$.ajax({
		url: 'command/find_transfer?account_id=' + $('#transfer_dlg #to_account_list').val() + "&amt=" + $('#transfer_dlg #amt').text() + "&posted=" + $('#transfer_dlg #sent').text(),
		success:function(data) {
			var ctrl = $('<select id="to_transaction_id"/>');
			$(data.transactions).each(function()
			{
				var option = $('<option />');
			    option.attr('value', this.id).text(this.posted);
			    ctrl.append(option);
			});
			$('#transfer_dlg #received').empty();
			$('#transfer_dlg #received').append(ctrl);
			}
		});
}

function check_rule(){
	$.ajax(
		{
			url: 'command/get_rule?name=' + $('#transaction_dlg #name').val(),
			async : false,
			cache : false,
			dataType: "json",
			success:function(data)
			{ 
				$(data.rule).each(function()
				{
					$('#transaction_dlg #vendor_list').children(":first").val(this.vendor);
					$('#transaction_dlg #category_list').children(":first").val(this.category);
				});
			}
		});
}